package com.xiaojie.controller;


import com.xiaojie.entity.Admin;
import com.xiaojie.service.IAdminService;
import constants.RedisPrefix;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xiaojie
 * @since 2022-07-27
 *
 * tokens 用户登录
 * admin-user 查询用户登录信息
 */
@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private IAdminService adminService;
    @Autowired
    private RedisTemplate<String, Object>  redisTemplate;
    @PostMapping("/tokens")
    public Map<String,String> tokens(@RequestBody Admin admin, HttpSession  session){
        //登录
        Admin login = adminService.login(admin);
        //登录成功获取Id
        String token = session.getId();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.opsForValue().set(RedisPrefix.TOKEN_KEY+token,login,30, TimeUnit.MINUTES);
        Map<String,String> map=new HashMap<>();
        map.put("token",token);
        return map;
    }
    @GetMapping("/admin-user")
    public Admin admin(String token){
       return (Admin) redisTemplate.opsForValue().get(RedisPrefix.TOKEN_KEY+token);
    }
    @DeleteMapping("/tokens/{token}")
    public void logout(@PathVariable("token") String token){
        redisTemplate.delete(RedisPrefix.TOKEN_KEY+token);
    }
}

